package com.cyj.springbootredis.Listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @description: 消息监听器
 * @Author C_Y_J
 * @create 2022/7/6 14:38
 **/
@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 接收消息的处理
     *
     * @param message message must not be {@literal null}.
     * @param pattern pattern matching the channel (if specified) - can be {@literal null}.
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("请求参数:{}_{}", message, pattern);
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        Object msgContent = redisTemplate.getValueSerializer().deserialize(body);
        Object topic = redisTemplate.getStringSerializer().deserialize(channel);
        log.info("反序列化请求参数:{}_{}", msgContent, topic);

        // 做业务逻辑 ...

    }
}
